//
//  HttpManageController.m
//  HouseShow
//
//  Created by  on 11-12-21.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "HttpManageController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "MainViewController.h"
#import "CJSONDeserializer.h"

#define DicObjectNull @"null"

@implementation HttpManageController
@synthesize m_MainVC;
@synthesize m_InitFirst;

#pragma -
#pragma 电子杂志
-(void) requestForMagzine:(NSInteger)index{
    NSDictionary* tLetfDic = [m_MainVC.m_LeftMenusArr objectAtIndex:index];
    NSString* tTidName =[tLetfDic objectForKey:@"tid"];
    //检测下基本数据是否已经获得
    NSString* tListFloder =[m_MainVC.m_OneListFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"list%d",index]];
    NSString* tListPlist = [tListFloder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",tTidName]];
    NSLog(@"path =%@",tListPlist);
    NSFileManager* tFManager = [NSFileManager defaultManager];
    if ([tFManager fileExistsAtPath:tListPlist]) {
        //存在
        if ([[m_MainVC.m_ListImgsArr objectAtIndex:index] isKindOfClass:[NSString class]]) {
            NSArray* tLocalList = [NSArray arrayWithContentsOfFile:tListPlist];
            [m_MainVC.m_ListImgsArr replaceObjectAtIndex:index withObject:tLocalList];
        }
        //呼叫flow动画
        if (m_MainVC.m_ShowSmallIndex == index) {
            m_MainVC.m_CallNextImgs = YES;
            if(m_InitFirst){
                m_InitFirst =NO;
                [m_MainVC showSmallImgDone];
            }
        }
    }else{
        id tListImgObject = [m_MainVC.m_ListImgsArr objectAtIndex:index];
        if ([tListImgObject isKindOfClass:[NSString class]]) {
            if ([tListImgObject isEqualToString:@"empty"]) {
                //不存在发起个请求
                NSString* tRequestPath = [NSString stringWithFormat:@"http://www.unitrue.com.cn:8088/ClientWebPage/CPlaneList.aspx?category=13&plane=%@",tTidName];
                NSLog(@"tRequestPath =%@",tRequestPath);
                ASIHTTPRequest* tLeftImgsListRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tRequestPath]];
                tLeftImgsListRequest.p_Tag = index;
                [m_MainVC.m_ListImgsArr replaceObjectAtIndex:index withObject:@"request"];
                [tLeftImgsListRequest setDelegate:self];
                [tLeftImgsListRequest setDidFailSelector:@selector(requestMagezinURLDidFail:)];
                [tLeftImgsListRequest setDidFinishSelector:@selector(requestMagezinFinishedURL:)];
                [tLeftImgsListRequest startAsynchronous];
            }
        }
    }
}

//杂志信息失败
-(void) requestMagezinURLDidFail:(ASIHTTPRequest*)request{
//    UIAlertView* tAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败，请检查网络后重新运行！" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];
//    tAlertView.tag =Alert_Menu;
//    [tAlertView show];
//    [tAlertView release];
    NSLog(@"杂志信息挂了");
}

//杂志基本数据请求成功
-(void) requestMagezinFinishedURL:(ASIHTTPRequest*)request{
    NSString* httpdata = [request responseString];
	NSLog(@"http context = %@",httpdata);
	NSData *jsonData = [httpdata dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSError *error = nil;
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] ;
	if (error == nil) {
        //请求菜单图片
        NSArray* tDataImgsArr = [tDataDic objectForKey:@"Plane"];
        NSMutableArray* tTempArr = [NSMutableArray arrayWithArray:tDataImgsArr];
        for (int i=0;i<[tTempArr count];i++) {
            NSMutableDictionary* tChangeDic = [NSMutableDictionary dictionaryWithDictionary:[tTempArr objectAtIndex:i]];
            [tChangeDic setObject:[tChangeDic objectForKey:@"pimg"] forKey:@"imgsrc"];//maximgsrc digest title
            [tChangeDic setObject:DicObjectNull forKey:@"maximgsrc"];
            [tChangeDic setObject:DicObjectNull forKey:@"digest"];
            [tChangeDic setObject:DicObjectNull forKey:@"title"];
            [tTempArr replaceObjectAtIndex:i withObject:tChangeDic];
        }
        [m_MainVC.m_ListImgsArr replaceObjectAtIndex:request.p_Tag withObject:tTempArr];
        
        //请求小图的杂志数据
        int index = 0;
        for (NSDictionary* object in tTempArr) {
            NSString* tImgURL = [object objectForKey:@"imgsrc"];
            ASIHTTPRequest* tLMRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tImgURL]];
            [tLMRequest setDelegate:self];
            tLMRequest.p_Tag =index+1000*request.p_Tag;
            [tLMRequest setDidFailSelector:@selector(MagezinImgRequestFail:)];
            [tLMRequest setDidFinishSelector:@selector(MagezinImgRequestFinish:)];
            [tLMRequest startAsynchronous];
            index++;
        }
    }
}

//请求杂志小的图片失败
-(void) MagezinImgRequestFail:(ASIHTTPRequest*)request{
    NSLog(@"杂志列表小图某张获得失败");
}
//请求杂志小的图片成功
-(void) MagezinImgRequestFinish:(ASIHTTPRequest*)request{
    NSData* tImgData = [request responseData];
    int tFloderIndex = request.p_Tag/1000;
    int tInListIndex = request.p_Tag%1000;
    NSMutableArray* tListArr =[NSMutableArray arrayWithArray:[m_MainVC.m_ListImgsArr objectAtIndex:tFloderIndex]];
    NSMutableDictionary* tOneImgDic =  [NSMutableDictionary dictionaryWithDictionary:[tListArr objectAtIndex:tInListIndex]];
    
    NSString* tSetFloderPath =[m_MainVC.m_OneListFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"list%d",tFloderIndex]];
    NSString* tSetSmallPath =[tSetFloderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"small%d",tInListIndex]];
    [tImgData writeToFile:tSetSmallPath atomically:YES];
    [tOneImgDic setObject:tSetSmallPath forKey:@"imgsrc"];
    [tListArr replaceObjectAtIndex:tInListIndex withObject:tOneImgDic];
    [m_MainVC.m_ListImgsArr replaceObjectAtIndex:tFloderIndex withObject:tListArr];
    
    BOOL tSmallImgOver = YES;
    for (NSDictionary* tEnumObject in tListArr) {
        NSString* tImgSrcStr = [tEnumObject objectForKey:@"imgsrc"];
        if ([tImgSrcStr rangeOfString:@"http"].location != NSNotFound) {
            tSmallImgOver = NO;
            break;
        }
    }
    if (tSmallImgOver) {
        NSDictionary* tLetfDic = [m_MainVC.m_LeftMenusArr objectAtIndex:tFloderIndex];
        NSString* tTidName =[tLetfDic objectForKey:@"tid"];
        NSString* tListPlist = [tSetFloderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",tTidName]];
        [tListArr writeToFile:tListPlist atomically:YES];
        
        //呼叫flow动画
        if (m_MainVC.m_ShowSmallIndex == tFloderIndex) {
            [m_MainVC showSmallImgDone];
        }
    }
}

//请求大图失败了
-(void) requestMagezinBigFail:(ASIHTTPRequest*)request{
    NSLog(@"杂志大图挂了");
}
//请求大图成功了
-(void) requestMagezinBigFinish:(ASIHTTPRequest*)request{
    NSString* httpdata = [request responseString];
	NSLog(@"http context = %@",httpdata);
	NSData *jsonData = [httpdata dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSError *error = nil;
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] ;
	if (error == nil) {
//        NSDictionary* tLetfDic = [m_MainVC.m_LeftMenusArr objectAtIndex:request.p_Tag];
//        NSString* tListName = [tLetfDic objectForKey:@"tid"];
//        
//        NSArray* tDataImgsArr = [tDataDic objectForKey:tListName];
//        NSMutableArray* tTempArr = [NSMutableArray arrayWithArray:tDataImgsArr];
//        [m_MainVC.m_ListImgsArr replaceObjectAtIndex:request.p_Tag withObject:tTempArr];
    }
}


#pragma -
#pragma 左菜单相关部分请求和处理
//左菜单数据请求
-(void) requestFlowImageData{
    NSFileManager* tFileMan = [NSFileManager defaultManager];
    NSString* tMenuPathDoc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* tMenuPath = [tMenuPathDoc stringByAppendingPathComponent:@"menudic.plist"];
    m_InitFirst =YES;
    if (![tFileMan fileExistsAtPath:tMenuPath]) {
        NSURL* tReqURL = [NSURL URLWithString:@"http://www.unitrue.com.cn:8088/ClientWebPage/CPlaneList.aspx?category=13"];
        ASIHTTPRequest* tRequest = [ASIHTTPRequest requestWithURL:tReqURL];
        [tRequest setDelegate:self];
        [tRequest setDidFailSelector:@selector(requestMenusURLDidFail:)];
        [tRequest setDidFinishSelector:@selector(requestFinishedMenusURL:)];
        [tRequest startAsynchronous];
    }else{
        //存在直接读
        m_MainVC.m_LeftMenusArr = [NSMutableArray arrayWithContentsOfFile:tMenuPath];
        [m_MainVC leftMenuMoveAnimate];
    }
}
//左菜单基本数据请求失败
-(void) requestMenusURLDidFail:(ASIHTTPRequest*)request{
    UIAlertView* tAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败，请检查网络后重新运行！" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    tAlertView.tag =Alert_Menu;
    [tAlertView show];
    [tAlertView release];
}

//左菜单基本数据请求成功
-(void) requestFinishedMenusURL:(ASIHTTPRequest*)request{
    NSString* httpdata = [request responseString];
	NSLog(@"http context = %@",httpdata);
	NSData *jsonData = [httpdata dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSError *error = nil;
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] ;
	if (error == nil) {
        //请求菜单图片
        m_MainVC.m_LeftMenusArr = [NSMutableArray arrayWithArray:[tDataDic objectForKey:@"Plane"]];
//        for (NSDictionary* object in m_MainVC.m_LeftMenusArr) {
//            NSString* tImgURL = [object objectForKey:@"pimg"];
//            ASIHTTPRequest* tLMRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tImgURL]];
//            [tLMRequest setDelegate:self];
//            [tLMRequest setDidFailSelector:@selector(leftMenuImgFail:)];
//            [tLMRequest setDidFinishSelector:@selector(leftMenuImgFinish:)];
//            [tLMRequest startAsynchronous];
//        }
        NSString* tMenuPathDoc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString* tMenuPath = [tMenuPathDoc stringByAppendingPathComponent:@"menudic.plist"];
        [m_MainVC.m_LeftMenusArr writeToFile:tMenuPath atomically:YES];
        [m_MainVC createImgsListFolder];
        [m_MainVC leftMenuMoveAnimate];
    }
}

////左菜单图请求失败
//-(void)leftMenuImgFail:(ASIHTTPRequest*)request{
//    NSLog(@"左侧图加载失败了");
//}
////左菜单图请求成功
//-(void)leftMenuImgFinish:(ASIHTTPRequest*)request{
//    NSString* tMenuPathDoc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString* tMenuPath = [tMenuPathDoc stringByAppendingPathComponent:@"menudic.plist"];
//    
//    NSMutableDictionary* tChangedDic = nil;
//    int index = 0;
//    for (NSDictionary* tScanDic in m_MainVC.m_LeftMenusArr) {
//        NSString* tURLStr = [tScanDic objectForKey:@"pimg"];
//        if ([tURLStr isEqualToString:[[request url] absoluteString]]) {
//            tChangedDic = [NSMutableDictionary dictionaryWithDictionary:tScanDic];
//            break;
//        }
//        index++;
//    }
//    NSData* tImgData = [request responseData];
//    NSString* tLMImg =[m_MainVC.m_LeftMenuFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"lefmenu%d",index]];
//    
//    [tImgData writeToFile:tLMImg atomically:YES];
//    [tChangedDic setObject:tLMImg forKey:@"pimg"];
//
//    [m_MainVC.m_LeftMenusArr replaceObjectAtIndex:index withObject:tChangedDic];
//    
//    BOOL allOverDone = YES;
//    for (tChangedDic in m_MainVC.m_LeftMenusArr) {
//        NSString* tURLStr = [tChangedDic objectForKey:@"pimg"];
//        if ([tURLStr rangeOfString:@"http"].location != NSNotFound) {
//            allOverDone = NO;
//            break;
//        }
//    }
//    if (allOverDone) {
//        [m_MainVC.m_LeftMenusArr writeToFile:tMenuPath atomically:YES];
//        [m_MainVC createImgsListFolder];
//        [m_MainVC leftMenuMoveAnimate];
//    }
//}


#pragma -
#pragma 右边列表图片请求和本地化

-(void) showImgsCheck:(NSInteger) index{
    NSDictionary* tLetfDic = [m_MainVC.m_LeftMenusArr objectAtIndex:index];
    NSString* tTidName =[tLetfDic objectForKey:@"tid"];
    //检测下基本数据是否已经获得
    NSString* tListFloder =[m_MainVC.m_OneListFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"list%d",index]];
    NSString* tListPlist = [tListFloder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",tTidName]];
    NSFileManager* tFManager = [NSFileManager defaultManager];
    if ([tFManager fileExistsAtPath:tListPlist]) {
        //存在
        if ([[m_MainVC.m_ListImgsArr objectAtIndex:index] isKindOfClass:[NSString class]]) {
            NSArray* tLocalList = [NSArray arrayWithContentsOfFile:tListPlist];
            [m_MainVC.m_ListImgsArr replaceObjectAtIndex:index withObject:tLocalList];
        }
        //呼叫flow动画
        if (m_MainVC.m_ShowSmallIndex == index) {
            m_MainVC.m_CallNextImgs = YES;
            if(m_InitFirst){
                m_InitFirst =NO;
                [m_MainVC showSmallImgDone];
            }
        }
    }else{
        id tListImgObject = [m_MainVC.m_ListImgsArr objectAtIndex:index];
        if ([tListImgObject isKindOfClass:[NSString class]]) {
            if ([tListImgObject isEqualToString:@"empty"]) {
                //不存在发起个请求
                NSString* tRequestPath = [NSString stringWithFormat:@"http://www.unitrue.com.cn:8088/ClientWebPage/CNewsList.aspx?tid=%@&begin=1&end=20",tTidName];
                NSLog(@"tRequestPath =%@",tRequestPath);
                ASIHTTPRequest* tLeftImgsListRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tRequestPath]];
                tLeftImgsListRequest.p_Tag = index;
                [m_MainVC.m_ListImgsArr replaceObjectAtIndex:index withObject:@"request"];
                [tLeftImgsListRequest setDelegate:self];
                [tLeftImgsListRequest setDidFailSelector:@selector(requestListImgs:)];
                [tLeftImgsListRequest setDidFinishSelector:@selector(requestListImgsFinish:)];
                [tLeftImgsListRequest startAsynchronous];
            }
        }
    }
}
//左侧列表图片数据获得失败 
-(void) requestListImgs:(ASIHTTPRequest*) request{
    NSLog(@"某一列表 小图序列数据获得失败");
}
//左侧列表图片数据获得成功
-(void) requestListImgsFinish:(ASIHTTPRequest*) request{
    NSString* httpdata = [request responseString];
	NSLog(@"http context = %@",httpdata);
	NSData *jsonData = [httpdata dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSError *error = nil;
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] ;
	if (error == nil) {
        NSDictionary* tLetfDic = [m_MainVC.m_LeftMenusArr objectAtIndex:request.p_Tag];
        NSString* tListName = [tLetfDic objectForKey:@"tid"];
        NSArray* tDataImgsArr = [tDataDic objectForKey:tListName];
        NSMutableArray* tTempArr = [NSMutableArray arrayWithArray:tDataImgsArr];
        [m_MainVC.m_ListImgsArr replaceObjectAtIndex:request.p_Tag withObject:tTempArr];
        
        int index = 0;
        for (NSDictionary* tListImgDic in tDataImgsArr) {
            NSString* tImgURL = [tListImgDic objectForKey:@"imgsrc"];
            ASIHTTPRequest* tListImgRequest =[ASIHTTPRequest requestWithURL:[NSURL URLWithString:tImgURL]];
            tListImgRequest.p_Tag = index+1000*request.p_Tag;
            [tListImgRequest setDelegate:self];
            [tListImgRequest setDidFailSelector:@selector(listImgRequestFail:)];
            [tListImgRequest setDidFinishSelector:@selector(listImgRequestFinish:)];
            [tListImgRequest startSynchronous];
            index++;
        }
    }
}
//请求右图的图片失败
-(void) listImgRequestFail:(ASIHTTPRequest*)request{
    NSLog(@"图片列表小图某张获得失败");
}
//请求右图的图片成功
-(void) listImgRequestFinish:(ASIHTTPRequest*)request{
    NSData* tImgData = [request responseData];
    int tFloderIndex = request.p_Tag/1000;
    int tInListIndex = request.p_Tag%1000;
    NSMutableArray* tListArr =[NSMutableArray arrayWithArray:[m_MainVC.m_ListImgsArr objectAtIndex:tFloderIndex]];
    NSMutableDictionary* tOneImgDic =  [NSMutableDictionary dictionaryWithDictionary:[tListArr objectAtIndex:tInListIndex]];
    
    NSString* tSetFloderPath =[m_MainVC.m_OneListFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"list%d",tFloderIndex]];
    NSString* tSetSmallPath =[tSetFloderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"small%d",tInListIndex]];
    [tImgData writeToFile:tSetSmallPath atomically:YES];
    [tOneImgDic setObject:tSetSmallPath forKey:@"imgsrc"];
    [tListArr replaceObjectAtIndex:tInListIndex withObject:tOneImgDic];
    [m_MainVC.m_ListImgsArr replaceObjectAtIndex:tFloderIndex withObject:tListArr];
    
    BOOL tSmallImgOver = YES;
    for (NSDictionary* tEnumObject in tListArr) {
        NSString* tImgSrcStr = [tEnumObject objectForKey:@"imgsrc"];
        if ([tImgSrcStr rangeOfString:@"http"].location != NSNotFound) {
            tSmallImgOver = NO;
            break;
        }
    }
    if (tSmallImgOver) {
        NSString* tListName = [tOneImgDic objectForKey:@"tid"];
        NSString* tListPlist = [tSetFloderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",tListName]];
        [tListArr writeToFile:tListPlist atomically:YES];
        
        //呼叫flow动画
        if (m_MainVC.m_ShowSmallIndex == tFloderIndex) {
            [m_MainVC showSmallImgDone];
        }
    }
}

@end
